/* -*- coding: utf-8; tab-width: 4 -*-
vim: ts=4 noet ai */

/**
	Desktopd Rainbow Persona -- Colorful Firefox

	Copyright © 2016  Desktopd Project

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as
	published by the Free Software Foundation, either version 3 of the
	License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

	@license GPL-3.0+
	@file
*/

'use strict';

const xyz = require ('./CIEXYZ');

const _f = t => t > 0.008856451679035631
	? Math.pow (t, 0.3333333333333333)
	: 7.787037037037037 * t + 0.13793103448275862;

const _g = t => t > 0.20689655172413793
	? Math.pow (t, 3)
	: 0.12841854934601665 * t - 0.017712903358071262;

/**
	L*, a*, b* values
	R, G, and B are in [0, 1]
*/
exports.fromRGB = (Xn, Yn, Zn, r, g, b) => {
	const [X, Y, Z] = xyz.fromRGB (r, g, b);
	const L = 116 * _f (Y / Yn) - 16;
	const A = 500 * (_f (X / Xn) - _f (Y / Yn));
	const B = 200 * (_f (Y / Yn) - _f (Z / Zn));
	return [L, A, B];
};

/**
	R, G, B values
	Inverse of the above
	Note: Resulting RGB may be out of range
*/
exports.toRGB = (Xn, Yn, Zn, L, A, B) => {
	const X = Xn * _g ((L + 16) / 116 + A / 500);
	const Y = Yn * _g ((L + 16) / 116);
	const Z = Zn * _g ((L + 16) / 116 - B / 200);
	return xyz.toRGB (X, Y, Z);
};

